//
//  IGIssueTopicViewController.m
//  jingdongfang
//
//  Created by BOE on 2017/8/16.
//  Copyright © 2017年 kevinLY. All rights reserved.
//

#import "IGIssueTopicVC.h"
#import "IGIssueTopicView.h"
#import "IGOSSManager.h"
#import "IGCommunityModel.h"
#import "IGIssueTopicApi.h"
#import "SVProgressHUD.h"
#import "AppDelegate.h"

@interface IGIssueTopicVC ()

//圈子ID
@property (nonatomic, strong) IGCommunityModel *communityModel;
//发布话题View
@property (nonatomic, strong) IGIssueTopicView *issueTopicView;
//发布图片
@property (nonatomic, strong) NSArray *selectedAssets;
@property (nonatomic, strong) NSMutableArray *picParams;
@property (nonatomic, strong) IGIssueTopicApi *api;

@end

@implementation IGIssueTopicVC
    
- (instancetype)initWithCommunityModel:(IGCommunityModel *)communityModel {
    if (self = [super init]) {
        self.communityModel = communityModel;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
//    self.title = @"发布新话题";
    self.title = NSLocalizedString(@"Post New Topic", nil);
    self.view.backgroundColor = [UIColor mainBackgroundColor];
    [self setAutomaticallyAdjustsScrollViewInsets:NO];
    
    /** accessToken有过期时间，所以在每次需要的时候重新请求 */
    [[IGOSSManager sharedManager] requestOssToken:IGAliYunFolderTypeCircle];
    [self addNotification];
    
    //rightItem
//    [self ig_setupRightButtonItemWithTitle:@"发布" image:nil highLightedImage:nil];
    [self ig_setupRightButtonItemWithTitle:NSLocalizedString(@"Post", nil) image:nil highLightedImage:nil];
    
    [self.view addSubview:self.issueTopicView];
}

#pragma mark - 懒加载
- (IGIssueTopicView *)issueTopicView {
    if (!_issueTopicView) {
        _issueTopicView = [[IGIssueTopicView alloc] initWithFrame:CGRectMake(0, NavigationMagin, KSCREENWIDTH, KSCREENHEIGHT - NavigationMagin) communityModel:self.communityModel];
    }
    return _issueTopicView;
}

- (NSArray *)selectedAssets {
    if (!_selectedAssets) {
        _selectedAssets = [NSArray array];
    }
    return _selectedAssets;
}

- (NSMutableArray *)picParams {
    if (!_picParams) {
        _picParams = [[NSMutableArray alloc] init];
    }
    return _picParams;
}

- (void)ig_rightButtonPressed:(id)sender {
    [self.issueTopicView.textView endEditing:YES];
//    [self showText:@"正在提交..."];
    [self showText:NSLocalizedString(@"Submitting", nil)];
    //公共的合法性校验
    NSString *text = _issueTopicView.textView.text;
    if ([text isEmpty]) {
//        [self presentMessageTips:@"请输入文字"];
        [self presentMessageTips:NSLocalizedString(@"Please Input Text", nil)];
        return;
    }
    
    if (_selectedAssets.count == 0 || _selectedAssets == nil) {
        [self publishTopicRequest];
    } else {
        [self asyncPutImages:_selectedAssets];
    }
}

- (void)asyncPutImages:(NSArray *)images {
    __weak typeof(self) weakSelf = self;
    [[IGOSSManager sharedManager] asyncPutImages:images withCompleteBlock:^(NSArray *params, NSArray *urls) {
        if (params.count != 0) {
            [weakSelf.picParams addObjectsFromArray:params];
            [weakSelf publishTopicRequest];
        } else {
//            [weakSelf presentMessageTips:@"发布失败!"];
            [weakSelf presentMessageTips:NSLocalizedString(@"Publication failed!", nil)];
        }
    }];
}

- (void)publishTopicRequest {
    self.api = [[IGIssueTopicApi alloc] init];
    self.api.imgs = self.picParams;
    self.api.circleId = self.issueTopicView.communityModel.cid;
    self.api.content = self.issueTopicView.textView.text;
    self.api.videos = @"";
    self.api.productId = self.issueTopicView.dataBase.aId;
    __weak typeof(self) weakSelf = self;
    [self.api startWithDecodeClass:[IGIssueTopicResp class] CompletionBlockWithSuccess:^(id responseObject, NSError *error) {
        if (responseObject) {
            [[NSNotificationCenter defaultCenter] postNotificationName:@"kTopicListRefresh" object:NSStringFromClass([weakSelf class])];
            [weakSelf presentMessageTips:NSLocalizedString(@"Post Successfully!", nil)];
            [weakSelf.navigationController popViewControllerAnimated:YES];
            if (weakSelf.autoRefresh) {
                weakSelf.autoRefresh();
            } else {
                [[kAPPDELEGATE rootTabBarVC] setSelectedIndex:2];
            }
        } else {
//            [weakSelf presentMessageTips:@"发布失败!"];
            [weakSelf presentMessageTips:NSLocalizedString(@"Post failed!", nil)];
        }
    }];
}
#pragma mark - Notifictaion
- (void)addNotification {
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(imageCollectionViewReloadNotifaction:) name:@"imageCollectionViewReloadNotifaction" object:nil];
}

- (void)imageCollectionViewReloadNotifaction:(NSNotification *)notification {
    NSArray *selectAssetsArr = (NSArray *)notification.object;
    self.selectedAssets = selectAssetsArr;
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"imageCollectionViewReloadNotifaction" object:nil];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
